/*
*   "name": "封装的本地存储方法"
*   "author": "huzhanlin(anlin)"
*   "keywords": [
*       "细节控制",
*       "本地缓存",
*       "new 类",
*       "多人协作",
*       "子类的命名",
*       ".结构形式"
*    ]
*   "age": {
*     const sess = new Db(2)
*     第一个参数为存储方式 -> 可选 默认为1
*     1为localStorage, 2为sessionStorage
*     const userLoc = new Db(1, 'user')
*     第二次参数为存储字段前的前缀-> 可选 默认为anlin
*   }
*/

export default class Db {
  constructor(status = 1, scope = 'anlin') {
    if (typeof status !== 'number' || typeof scope !== 'string') {
      alert('传入的参数格式不正确,将使用默认的参数配置')
      this.scope = 'anlin'
      this.status = 1
    } else {
      this.scope = scope
      this.status = status
    }
  }

  setItem (key, value, item) {
    item.setItem(this.scope + '_' + key, JSON.stringify(value))
  }
  set (key, value) {
    if (this.status === 1) {
      this.setItem(key, value, localStorage)
    } else {
      this.setItem(key, value, sessionStorage)
    }
  }

  getItem (key, item) {
    try {
      return JSON.parse(item.getItem(this.scope + '_' + key))
    } catch {
      return null
    }
  }
  get (key) {
    if (this.status === 1) {
      return this.getItem(key, localStorage)
    } else {
      return this.getItem(key, sessionStorage)
    }
  }

  clearItem (item) {
    for (const key in item) {
      if (key.indexOf(this.scope) !== -1) {
        item.removeItem(key)
      }
    }
  }
  clear () {
    if (this.status === 1) {
      this.clearItem(localStorage)
    } else {
      this.clearItem(sessionStorage)
    }
  }

  removeItem (key, item) {
    item.removeItem(this.scope + '_' + key)
  }
  remove (key) {
    if (this.status === 1) {
      this.removeItem(key, localStorage)
    } else {
      this.removeItem(key, sessionStorage)
    }
  }
}

// const loc = new Db()
// const sess = new Db(2)
// const userLoc = new Db(1, 'user')
// const userSess = new Db(2, 'user')

// export default { loc, sess, userLoc, userSess }
